﻿using System.Security.Claims;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace Topro.Admin.Controllers
{
    using Topro.Util;
    using Topro.Entity.Request.Login;
    using Topro.Application.Interface;

    /// <summary>
    /// 登录控制器
    /// </summary>
    public class AccountController : Controller
    {
        #region 注入
        /// <summary>
        /// 用户
        /// </summary>
        private readonly LoginService _loginService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataBase">菜单</param>
        public AccountController(LoginService loginService)
        {
            _loginService = loginService;
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request">参数</param>
        [HttpPost]
        public async Task<JsonResult> Login(LoginRequest request)
        {
            //登录
            var response = _loginService.Login(request);

            //验证
            if (response.Success && response.Data != null)
            {
                var json = response.Data.UserPermissions != null ? string.Join(", ", response.Data.UserPermissions) : "";

                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Sid,response.Data.UserId.ToString()),
                    new Claim(ClaimTypes.Name,response.Data.UserName),
                    new Claim(ClaimTypes.Role,EncryptionUtil.EnCryptDES(json))
                };

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

                response.Success = true;
                response.Message = "登录成功.";
            }

            return Json(response);
        }
        #endregion

        #region 注销
        /// <summary>
        /// 注销
        /// </summary>
        public IActionResult Logout()
        {
            Task.Run(async () =>
            {
                await HttpContext.SignOutAsync();
            }).Wait();

            return View("Index");
        }
        #endregion
    }
}
